package org.rslai.tcedit.dao.hibernate;

import java.util.List;
import org.rslai.tcedit.dao.ExecuteStateDao;
import org.rslai.tcedit.domain.ExecuteState;
import org.rslai.tcedit.domain.Page;
import org.rslai.tcedit.exception.ApplicationException;

/**
 * ExecuteStateDao 的实现类
 * 
 * @author rslai
 * 
 * @spring.bean id="executeStateDao"
 */
public class ExecuteStateImpl extends GenericHibernateDao<ExecuteState> implements ExecuteStateDao {

	public ExecuteStateImpl() {
		super(ExecuteState.class);
	}

	/**
	 * 创建一个 ExecuteState 信息。覆盖 GenericHibernateDao 中的 create 方法。
	 * 
	 * @param executeState ExecuteState对象
	 */
	public void create(ExecuteState executeState) {
		ExecuteState tmpExecuteState = (ExecuteState) queryForObject(
				"from ExecuteState as a where a.name=?",
				new Object[] { executeState.getName() }
		);
		if (tmpExecuteState != null) {
			throw new ApplicationException("您输入的“测试用例执行状态名”已存在，请重新输入。");
		}

		hibernateTemplate.save(executeState);
	}
	
	/**
	 * 更新一个 CaseState 信息。覆盖 GenericHibernateDao 中的 update 方法。
	 * 
	 * @param executeState ExecuteState 对象
	 */
	public void update(ExecuteState executeState) {
		ExecuteState tmpExecuteState = (ExecuteState) queryForObject(
				"from ExecuteState as a where a.name=? and a.id!=?",
				new Object[] { executeState.getName(), executeState.getId() }
		);
		if (tmpExecuteState != null) {
			throw new ApplicationException("您输入的“测试用例执行状态名”已存在，请重新输入。");
		}

		hibernateTemplate.update(executeState);
	}

    private static final String QUERY_EXECUTE_STATE_ASC = "from ExecuteState as a where a.name LIKE ? order by a.sequence";
    private static final String QUERY_EXECUTE_STATE_DESC = "from ExecuteState as a where a.name LIKE ? order by a.sequence desc";

    @SuppressWarnings("unchecked")
	public List<ExecuteState> query(Page page, String name, boolean asc) {
		return queryForList(
				"select count(*) from ExecuteState as a where a.name LIKE ?",
				asc ? QUERY_EXECUTE_STATE_ASC : QUERY_EXECUTE_STATE_DESC, 
				new Object[] { name },
				page
		);
	}

}
